package com.collins.thread.practices.drawLottery;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public class LotteryBoxCallable implements Callable<Integer> {
    // thread owned data list
    private List<Integer> lotteryList = new ArrayList<>();
    // time format
    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Integer call() throws Exception {
        while (true) {
            synchronized (Host.lock) {
                if (Host.lotteries.isEmpty()) {
                    break;
                } else {
                    TimeUnit.MILLISECONDS.sleep(10);
                    // switcher on
                    String name = Thread.currentThread().getName();
//                    System.out.println(df.format(new Date(System.currentTimeMillis())) + "-"
//                            + name + " is drawing lottery ... ");
                    if (Integer.parseInt(name.substring(name.length() - 1)) == Host.flag) {
                        Collections.shuffle(Host.lotteries);
                        lotteryList.add(Host.lotteries.remove(0));
                        // reset flag
                        Host.flag = Host.random.nextInt(Host.boxNum);
                    }
                    // switcher off
                }
            }
        }
        Thread.sleep(10);
        // when all lotteries being drew, do following:
        // print all lotteries
        System.out.println(Thread.currentThread().getName() + " has lotteries: " + lotteryList);
        if (lotteryList.isEmpty()) {
            return null;
        }
        return Collections.max(lotteryList);
    }
}
